package com.xcc;

import com.xcc.app.App;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyThread implements Runnable {
    private static MyThread myThread;
    private boolean isRuning;
    private ServerSocket serverSocket;
    /*public static MyThread getInstance() {
        if (myThread == null) {
            synchronized (MyThread.class) {
                if (myThread == null) myThread = new MyThread();
            }
        }
        return myThread;
    }*/

    @Override
    public void run() {
        /*while (isRuning) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (isRuning) {
                System.out.println("MyThread_runing" + System.currentTimeMillis());
            } else System.out.println("MyThread_end");
        }*/
        App app = new App();
        try {
            serverSocket = new ServerSocket(10115);
            while (isRuning) {
                Socket accept = serverSocket.accept();
                TCPClient client = new TCPClient(accept, app);
                client.start();
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        System.out.println("MyThread_end");
    }

    public synchronized static void start() {
        if (myThread == null) {
            myThread = new MyThread();
            myThread.isRuning = true;
            new Thread(myThread).start();
        }
    }

    private void stop_() {
        isRuning = false;
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized static void stop() {
        if (myThread == null) return;
        myThread.stop_();
        myThread = null;
    }

    public synchronized static boolean isRuning() {
        if (myThread == null) return false;
        return myThread.isRuning;
    }
}
